package cn.ztydata.teachingsystem.heaven.web.controller;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.heaven.common.WebContext;
import cn.ztydata.teachingsystem.heaven.cons.MsgTemplate;
import cn.ztydata.teachingsystem.heaven.entity.Resource;
import cn.ztydata.teachingsystem.heaven.service.DepartmentService;
import cn.ztydata.teachingsystem.heaven.service.ResourceService;
import cn.ztydata.teachingsystem.heaven.service.TeacherTeamService;
import cn.ztydata.teachingsystem.heaven.web.dto.CourseRscDto;
import cn.ztydata.teachingsystem.heaven.web.dto.ResourceListDto;
import cn.ztydata.teachingsystem.util.StringCodeUtil;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResult;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultData;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultId;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultPage;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

/**
 * 课程资源控制器类
 * Created by chenxin on 2014/12/18.
 */
@Controller
@RequestMapping("/lessonResource")
public class LessonRscController extends BaseController {
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private TeacherTeamService teacherTeamService;

    @Autowired
    private WebContext webContext;

    /**
     * 获取课程资源列表
     *
     * @author chenxin
     * @since 2014/12/18
     */
    @RequestMapping(value = "/list/{pageNum}/{pageSize}/{courseId}/{typeId}/{mediaType}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultPage<ResourceListDto> getList(@PathVariable int pageNum, @PathVariable int pageSize, @PathVariable long courseId,
                                                   @PathVariable int typeId, @PathVariable int mediaType,
                                                   @RequestParam(value = "knowledgeId") Long kpId,
                                                   @RequestParam(required = false) String keyword, @RequestParam(required = false) String author) {
        if (kpId == null) { //搜索的知识点不存在
            log.debug("搜索的知识点不存在:kpId == null");
            List<ResourceListDto> result = Lists.newArrayList();
            return new JsonResultPage<>(new Page<>(0, pageSize, pageNum, result));
        }

        //校验参数
        Assert.isTrue(pageNum > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "页码"));
        Assert.isTrue(pageSize > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "每页条数"));
        Assert.isTrue(courseId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "课程ID"));
        Assert.isTrue(typeId >= 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "资源类型"));
        Assert.isTrue(mediaType >= 0 && mediaType <= 4, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "媒体类型"));
        Assert.isTrue(kpId >= 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "知识点ID"));

        //中文转码
        keyword = StringCodeUtil.urlParamTransCode(keyword, StringCodeUtil.UTF8);
        author = StringCodeUtil.urlParamTransCode(author, StringCodeUtil.UTF8);

        //获取课程资源
        Page<Resource> page = resourceService.getListForCourse(pageNum, pageSize, courseId, typeId, mediaType, keyword, author, kpId);
        //映射到dto类
        Page<ResourceListDto> result = new Page<>(page.getTotal(), pageSize, pageNum, mapper.mapList(page.getItems(), ResourceListDto.class));

        log.debug("获取课程资源列表");
        return new JsonResultPage<>(result);
    }

    /**
     * 新增课程资源
     *
     * @author chenxin
     * @since 2014/12/24
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult saveRscInfo(@Valid @RequestBody CourseRscDto courseRscDto) {
        //映射到实体类
        Resource resource = mapper.map(courseRscDto, Resource.class);
        //设置上传者ID
        resource.setUploaderId(webContext.getUserId());

        //获取系部ID
        long deptId = departmentService.getIdBySpecialtyId(resource.getSpecialtyId());
        if (deptId == 0) {
            log.debug("无效的系部ID:deptId == 0");
            log.warn("无效的系部ID:deptId->0,specId->" + resource.getSpecialtyId());
            return new JsonResultId(false, "保存失败");
        }
        resource.setDeptId(deptId);

        //判断用户是否在课程的教师团队
        teacherTeamService.isMemeber(resource.getCourseId());

        //保存新增的资源信息
        resourceService.add(resource);

        log.debug("新增课程资源");
        return new JsonResultId(resource.getId(), "保存成功");
    }

    /**
     * 获取课程资源的统计信息
     *
     * @author chenxin
     * @since 2014/12/19
     */
    @RequestMapping(value = "/statistics/{courseId}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultData<Map<String, Object>> getStatistics(@PathVariable long courseId) {
        //校验参数
        Assert.isTrue(courseId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, courseId));

        //获取统计结果
        Map<String, Object> result = resourceService.getStatisticForMedia(0, courseId);

        log.debug("获取课程资源的统计信息");
        return new JsonResultData<>(result);
    }

    /**
     * 删除课程资源
     *
     * @author chenxin
     * @since 2014/12/24
     */
    @RequestMapping(value = "/remove/{rscId}/{courseId}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResult deleteCourseRsc(@PathVariable long rscId, @PathVariable long courseId) {
        //校验参数
        Assert.isTrue(rscId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "资源ID"));
        Assert.isTrue(courseId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "课程ID"));

        try {
            //删除课程资源
            resourceService.deleteForCourse(rscId, courseId);
        } catch (ServiceException ex) {
            log.debug("删除课程资源失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "删除失败" : ex.getMessage());
        }

        log.debug("删除课程资源");
        return new JsonResult(true, "删除成功");
    }

    /**
     * 搜索课程资源（章节）
     *
     * @author chenxin
     * @since 2014/12/18
     */
    @RequestMapping(value = "/relatedList/{pageNum}/{pageSize}/{courseId}/{nodeId}/{typeId}/{mediaType}/{related}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultPage<ResourceListDto> getListForSearch(@PathVariable int pageNum, @PathVariable int pageSize,
                                                            @PathVariable long courseId, @PathVariable long nodeId,
                                                            @PathVariable int typeId, @PathVariable int mediaType,
                                                            @PathVariable int related, @RequestParam(required = false) String keyword) {
        //校验参数
        Assert.isTrue(pageNum > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "页码"));
        Assert.isTrue(pageSize > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "每页条数"));
        Assert.isTrue(courseId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "课程ID"));
        Assert.isTrue(nodeId >= 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "章节ID"));
        Assert.isTrue(typeId >= 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "资源类型"));
        Assert.isTrue(mediaType >= 0 && mediaType <= 4, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "媒体类型"));
        Assert.isTrue(related >= 0 && related <= 1, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "关联知识点标识"));

        //中文转码
        keyword = StringCodeUtil.urlParamTransCode(keyword, StringCodeUtil.UTF8);

        //获取课程资源
        Page<Resource> page = resourceService.getListForSearch(pageNum, pageSize, courseId, nodeId, typeId,
                mediaType, keyword, related > 0, true);
        //映射到dto类
        Page<ResourceListDto> result = new Page<>(page.getTotal(), pageSize, pageNum, mapper.mapList(page.getItems(), ResourceListDto.class));

        log.debug("获取课程资源列表");
        return new JsonResultPage<>(result);
    }
}
